<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="dev-api/admin/product/upload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success='handleUploadSuccess'
        >

          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectAttrList.length}个未选`" v-model="attrIdAndAttrName">
          <el-option :label="attr.name" :value="`${attr.id}:${attr.name}`" v-for="(attr,index) in unSelectAttrList" :key="attr.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <el-table border :data="spuInfo.spuSaleAttrList" style="width: 100%" >
          <el-table-column align="center" type="index" label="序号" width="80px">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名">
          </el-table-column>
          <el-table-column prop="columnProp" label="属性值名称列表">
            <template slot-scope="scope">
              <el-tag :key="index" v-for="(attr,index) in scope.row.spuSaleAttrValueList"
                      closable :disable-transitions="false"
                      @close="handleClose(scope.row,index)"
              >
                {{attr.saleAttrValueName}}
              </el-tag>
              <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                        @blur="handleInputConfirm(scope.row)"
                        @keydown.enter.native="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(scope.row)" >+ 添加属性</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="columnProp" label="操作">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="deleteAttr(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="SaveOrUpdateSpuInfo">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

export default {
  name: "SpuForm",
  data() {
    return {
      spuInfo:{//商品信息
          category3Id: 0,
          description: "",//商品描述
          spuName: "",//商品名
          tmId: 0,
          spuImageList: [
            {
              id: 0,
              imgName: "",
              imgUrl: "",
              spuId: 0
            }
          ],
          spuSaleAttrList: [
            // {
            //   baseSaleAttrId: 0,
            //   id: 0,
            //   saleAttrName: "",
            //   spuId: 0,
            //   spuSaleAttrValueList: [
            //     {
            //       baseSaleAttrId: 0,
            //       id: 0,
            //       isChecked: "",
            //       saleAttrName: "",
            //       saleAttrValueName: "",
            //       spuId: 0
            //     }
            //   ]
            // }
          ],
        },
      tradeMarkList: [],//品牌信息列表
      saleAttrList: [],//销售属性列表
      spuImageList: [],//spu图片列表
      attrIdAndAttrName: "", //收集未选择的销售属性的id

      //照片墙控制参数
      dialogImageUrl: '',
      dialogVisible: false,

    };
  },
  computed:{
    unSelectAttrList(){
      const list=this.saleAttrList.filter((item)=>{
        return this.spuInfo.spuSaleAttrList.every((item2)=>{
          return item.name!=item2.saleAttrName;
        })
      })
      return list;
    },
  },
  methods: {
    //照片墙回调函数
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess(response, file, fileList){
      //response：上传图片的响应的返回值，file：上传的文件，fileList：上传完成之后的图片库
      console.log(response,file,fileList)
      if(response.code==200&&file.response.code==200){
        this.spuImageList=fileList;
      }
    },
    //初始化数据
    async initSpuFormData(id) {
      // console.log(id, '加载数据中');
      //获取商品信息byId
      const spuInfoResult = await this.$API.default.spu.reqSpuInfo(id);
      if (spuInfoResult.code == 200) {
        this.spuInfo = spuInfoResult.data;
      }
      //获取品牌列表信息
      const tradeMarkListResult = await this.$API.default.spu.reqTradeMarkList();
      if (tradeMarkListResult.code == 200) {
        this.tradeMarkList = tradeMarkListResult.data;
      }
      //获取销售属性列表信息
      const saleAttrResult = await this.$API.default.spu.reqSaleAttrList();
      if (saleAttrResult.code == 200) {
        this.saleAttrList = saleAttrResult.data;
      }
      //获取spu商品信息的图片列表
      const ImageListResult = await this.$API.default.spu.reqSpuImageList(id);
      if (ImageListResult.code == 200) {
        this.spuImageList = ImageListResult.data;
        this.spuImageList.forEach(item =>{
          item.name=item.imgName;
          item.url=item.imgUrl;
        })
      }
    },
    //当父组件点击添加属性的按钮时，初始化数据
    async addInitSpuFormData(id){
      // console.log(id);
      this.spuInfo.category3Id=id;
      //获取品牌列表信息
      const tradeMarkListResult = await this.$API.default.spu.reqTradeMarkList();
      if (tradeMarkListResult.code == 200) {
        this.tradeMarkList = tradeMarkListResult.data;
      }
      //获取销售属性列表信息
      const saleAttrResult = await this.$API.default.spu.reqSaleAttrList();
      if (saleAttrResult.code == 200) {
        this.saleAttrList = saleAttrResult.data;
      }
    },
    //添加销售属性按钮的回调
    addSaleAttr(){
      const attrObj={
        baseSaleAttrId:null,
        saleAttrName:"",
        spuId:null,
        spuSaleAttrValueList:[],
      }
      attrObj.saleAttrName=this.attrIdAndAttrName.split(':')[1]
      attrObj.baseSaleAttrId=this.attrIdAndAttrName.split(':')[0];
      attrObj.spuId=this.spuInfo.id;
      console.log(attrObj);
      this.spuInfo.spuSaleAttrList.push(attrObj);
      //清空选择框数据
      this.attrIdAndAttrName="";
    },
    //删除销售属性按钮的回调
    deleteAttr(index){
      // console.log(index);
      this.spuInfo.spuSaleAttrList.splice(index,1);
    },
    //保存或修改spuInfo按钮的回调
    async SaveOrUpdateSpuInfo(){
      // console.log(this.spuImageList);
      this.spuInfo.spuImageList=this.spuImageList.map((item)=>{
        return{
          imgName:item.name,
          imgUrl:(item.response && item.response.data) || item.url
        }
      })
      //发起请求
      // console.log(this.spuInfo)
      const result=await this.$API.default.spu.reqSaveOrUpdateSpuInfo(this.spuInfo);
      // console.log(result)
      if(result.code==200){
        this.$message({
          type:'success',
          message:'保存成功'
        });
        if(this.spuInfo.id){
          //有id,为修改
          this.$emit('cancelSpuForm', {scene:0,page:undefined})
        }else{//无id，为保存,跳转到第一页
          this.$emit('cancelSpuForm', {scene:0,page:1})
        }
      }
      //清除数据
      Object.assign(this._data,this.$options.data());
    },
    //取消保存按钮的回调
    cancel(){
      this.$emit('cancelSpuForm', {scene:0,page:undefined})
      Object.assign(this._data,this.$options.data());
    },

    //面包屑tag控制回调
    handleClose(row,index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },
    addSaleAttrValue(row) {
      //点击销售属性值当中添加按钮的时候，需要有button变为input,通过当前销售属性的inputVisible控制
        //面包屑tag控制参数
        // inputVisible: false,
        // inputValue: '',
      console.log(row);
      this.$set(row, "inputVisible", true);
      //通过响应式数据inputValue字段收集新增的销售属性值
      this.$set(row, "inputValue", "");
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus();//.$refs.input
      });
    },
    handleInputConfirm(row) {
      const  newAttrValue={
        // baseSaleAttrId:null,
        // id:null,
        // isChecked:null,
        // saleAttrName:"",
        // saleAttrValueName:"",
        // spuId:null
      }
      //结构row属性
      const {inputValue,baseSaleAttrId,spuId,saleAttrName}=row
      newAttrValue.saleAttrValueName=inputValue;
      newAttrValue.baseSaleAttrId=baseSaleAttrId;
      newAttrValue.spuId=spuId;
      newAttrValue.saleAttrName=saleAttrName;
      // console.log(newAttrValue)
      if(newAttrValue.saleAttrValueName.trim()==''){
        this.$message({
          message:'属性值不能为空',
          type:'warning'
        });
        row.inputVisible=false;
        return ;
      }
      let result=row.spuSaleAttrValueList.some((item)=>{
        return newAttrValue.saleAttrValueName==item.saleAttrValueName;
      })
      // console.log(result);
      if(result){
        this.$message({
          message:'属性值不能重复',
          type:'warning'
        })
      }else{
        row.spuSaleAttrValueList.push(newAttrValue);
      }
      row.inputVisible=false;//切换input和button的展示
    },
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
